/*###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.9
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############*/



function tb_reinit(domChunk) {
	$(domChunk).unbind("click");
	tb_init(domChunk);
}


// Sourced online 20101002
//http://snippets.dzone.com/posts/show/2069

function JFXUpdateStylesheets() {
	var i,a,s;
	a=document.getElementsByTagName('link');
	for(i=0;i<a.length;i++) {
		s=a[i];
		if(s.rel.toLowerCase().indexOf('stylesheet')>=0&&s.href) {
			var h=s.href.replace(/(&|\\?)JFXForceReload=d /,'');
			s.href=h+(h.indexOf('?')>=0?'&':'?')+'forceReload='+(new Date().valueOf());
		}
	}
}

/*
 * Called once per page load, not called again after ajax load
 */
function JFXOnloadOnce(){
    // load codepress

    // accordion left menu
	if($('#accordion').accordion){
		$("#accordion").accordion({ header: "h3", collapsible : 'true', active : JFXConfig.defaultMenuOpen });
	}

    //hover states on the static widgets
    $('#dialog_link, ul#icons li').hover(
        function() { $(this).addClass('ui-state-hover'); },
        function() { $(this).removeClass('ui-state-hover'); }
    );

    // save the accordion open status in session via ajax
    $('#jfx-leftcol-menu h3 a').click(function(){
        var id = this.id.replace('jfx-leftcol-menu-', '');
        $.get(JFXConfig.themeAdminUrl+'/log-menu-open/', {'id' : id});
    });
/*
    tinyMCE.init({mode : "textareas",
                  editor_selector: "tinymce",
                  theme: "advanced",
                  customvalue: "a custom value",
                  relative_urls: false,
                  convert_urls: false,
                  plugins: "emotions,jfxlinker",
                  theme_advanced_buttons3_add: "emotions,jfxlinker"
                  });
*/






    // make pages menu redirect the whole page instead of load ajax content
    $('#jfx-pages-menu a').each(function(){
        if(!$(this.parentNode).hasClass('redirect')) $(this.parentNode).addClass('redirect');
    });

    // make each link in the left menu load content via ajax
    $('#jfx-leftcol-menu a').each(function(){
		JFXAjaxLink(this);
	});

    // make pages menu draggable
	if($('#jfx-pages-menu').draggable){
		$('#jfx-pages-menu').draggable({handle:'#jfx-pages-menu-drag-handle'});
	}
    // make pages menu into treeview
	if($("#jfxcore-draggable-page-tree").treeview){
		$("#jfxcore-draggable-page-tree").treeview({
			persist: "location",
			collapsed: true,
			unique: true
		});
	}

    // pages menu close button hover animation
    $('#jfx-pages-menu-close').hover(function(){
        $('img', this).attr('src', $('img', this).attr('src').replace('-normal', '-hover'));
    },function(){
        $('img', this).attr('src', $('img', this).attr('src').replace('-hover', '-normal'));
    });

    // able to delete pages from the page menu
    $("#jfxcore-draggable-page-tree .jfx-delete").click(function(){
        return true;
    });

    // add a fade-in animation for showing page tree
    $('#jfx-pages').click(function(){
        $('#jfx-pages-menu').fadeIn('slow');
        return false;
    });

    // add a fade-out animation for hiding page tree
    $('#jfx-pages-menu-close').click(function(){
        $('#jfx-pages-menu').fadeOut('slow');
    });

}


function JFXAjaxLink(a){
	$(a).click(function(){
        if($(this.parentNode).hasClass('redirect')) return true;
	if($(this).attr('href').toLowerCase().indexOf('redirect')>=0 && this.href) return true;
        var href = $(this).attr('href');
        if(href === 'javascript: void(null)' || href === '#') return;
        JFXShowLoadingAnimation();
	$('.jfxt-success-messages').each(function(){
		$(this).css('display', 'none');
	});
	$('.jfxt-error-messages').each(function(){
		$(this).css('display', 'none');
	});
        $.getJSON(href, {'JFXGetAjaxContent' : '1'}, JFXParseAjaxContent);
        return false;
    });
}







/*
 * Called once on every page load, even called again after ajax load
 */
function JFXOnloadAlways(){

	// manual reload button
	$('#jfx-rebuild').click(function(){
		AdminBlocks.rebuildPage();
	});

    // links inside thickbox are meant to redirect the whole window
    $('.jfx-thickbox a').each(function(){
        if(!$(this.parentNode).hasClass('redirect')) $(this.parentNode).addClass('redirect');
    });

    // make the select menus to load content via ajax
    $('#jfx-module-select').each(function(){
        var lang, langSel, url, params;
        $(this).unbind('change');
        $(this).change(function(e){
            $(this).unbind('change');
            if($('#jfx-lang-select').get().length > 0){
                langSel = $('#jfx-lang-select').get(0);
                lang = langSel.options[langSel.selectedIndex].value;
            }else{
                lang = '';
            }
            url = JFXConfig.adminUrl+'/lang/translate/';
            params = {'lang' : lang, 'module' : this.options[this.selectedIndex].value, 'JFXGetAjaxContent' : '1'};
            JFXShowLoadingAnimation();
            $.getJSON(url, params, JFXParseAjaxContent);
            return false;
        });
    });

    // make the select menus to load content via ajax
    $('#jfx-lang-select').each(function(){
        $(this).unbind('change');
        $(this).change(function(){
            $(this).unbind('change');
            if($('#jfx-module-select').get().length > 0){
                var moduleSel = $('#jfx-module-select').get(0);
                var module = moduleSel.options[moduleSel.selectedIndex].value;
            }else{
                var module = '';
            }
            var url = JFXConfig.adminUrl+'/lang/translate/';
            var params = {'module' : module, 'lang' : this.options[this.selectedIndex].value, 'JFXGetAjaxContent' : '1'};
            JFXShowLoadingAnimation();
            $.getJSON(url, params, JFXParseAjaxContent);
            return false;
        });
    });

    // make the select menus to load content via ajax
    $('#jfx-workspace-select').each(function(){
        $(this).unbind('change');
        $(this).change(function(){
            $(this).unbind('change');
            var url = JFXConfig.adminUrl+'/workspaces/assign/';
            var params = {'workspace' : this.options[this.selectedIndex].value, 'JFXGetAjaxContent' : '1'};
            JFXShowLoadingAnimation();
            $.getJSON(url, params, JFXParseAjaxContent);
            return false;
        });
    });

    // make the select menus to load content via ajax
    $('#jfx-workspace-perms-select').each(function(){
        $(this).unbind('change');
        $(this).change(function(){
            $(this).unbind('change');
            var url = JFXConfig.adminUrl+'/perms/';
            var userSel = $('#jfx-user-perms-select').get(0);
            var userid = userSel.options[userSel.selectedIndex].value;
            var params = {'workspace' : this.options[this.selectedIndex].value, 'user' : userid, 'JFXGetAjaxContent' : '1'};
            JFXShowLoadingAnimation();
            $.getJSON(url, params, JFXParseAjaxContent);
            return false;
        });
    });

    // make the select menus to load content via ajax
    $('#jfx-user-perms-select').each(function(){
        $(this).unbind('change');
        $(this).change(function(){
            $(this).unbind('change');
            var url = JFXConfig.adminUrl+'/perms/';
            var workspaceSel = $('#jfx-workspace-perms-select').get(0);
            var workspaceid = workspaceSel.options[workspaceSel.selectedIndex].value;
            var params = {'workspace' : workspaceid, 'user' : this.options[this.selectedIndex].value, 'JFXGetAjaxContent' : '1'};
            JFXShowLoadingAnimation();
            $.getJSON(url, params, JFXParseAjaxContent);
            return false;
        });
    });

    // make the select menus to load content via ajax
    $('#jfx-workspace-select-to').each(function(){
        $(this).unbind('change');
        $(this).change(function(){
            $(this).unbind('change');
            if($('#jfx-workspace-select-from').get().length > 0){
                var fromSel = $('#jfx-workspace-select-from').get(0);
                var from = fromSel.options[fromSel.selectedIndex].value;
            }else{
                var from = '';
            }
            var url = JFXConfig.adminUrl+'/workspaces/copy/';
            var params = {'to' : this.options[this.selectedIndex].value, 'from' : from, 'JFXGetAjaxContent' : '1'};
            JFXShowLoadingAnimation();
            $.getJSON(url, params, JFXParseAjaxContent);
            return false;
        });
    });

    // make the select menus to load content via ajax
    $('#jfx-workspace-select-from').each(function(){
        $(this).unbind('change');
        $(this).change(function(){
            $(this).unbind('change');
            if($('#jfx-workspace-select-to').get().length > 0){
                var toSel = $('#jfx-workspace-select-to').get(0);
                var to = toSel.options[toSel.selectedIndex].value;
            }else{
                var to = '';
            }
            var url = JFXConfig.adminUrl+'/workspaces/copy/';
            var params = {'from' : this.options[this.selectedIndex].value, 'to' : to, 'JFXGetAjaxContent' : '1'};
            JFXShowLoadingAnimation();
            $.getJSON(url, params, JFXParseAjaxContent);
            return false;
        });
    });


}



function JFXAjaxSubmitSuccess(rsp){
    //alert('success'+rsp);
    try{
        var json = JSON.parse(rsp);
        JFXParseAjaxContent(json);
    }catch (e){
        //$.post(JFXConfig.themeAdminUrl, {'logdata' : rsp});
        //window.location = JFXConfig.themeAdminUrl+'/failed-ajax-submit/';
        alert('caught exception trying to decode response, length: '+rsp.length);
		console.log(e.toString());
    }
}

function JFXShowLoadingAnimation(){
	if($('#jfx-page-workspace-loading-animation').get().length > 0){
		return;
	}
	var loadingAnimation = document.createElement('div');
	var img = document.createElement('img');
	img.src = JFXConfig.loadingAnimationSource;
	img.alt = JFXConfig.loadingAnimationAlt;
	loadingAnimation.appendChild(img);
	loadingAnimation.id = 'jfx-page-workspace-loading-animation';
	$('#jfx-page-workspace-inner .jfx-page').append(loadingAnimation);
}

function JFXHideLoadingAnimation(){
	$('#jfx-page-workspace-loading-animation').remove();
}

function JFXToggleStats(){
	$('#jfxt-debugging').toggle();
}

function JFXParseAjaxContent(json){
    var newScripts, scripts, foundScripts, i, i2, head, script, style, newAction, ajaxSubmitOptions;

	if(!json) return;

    $('#jfx-workspace-inner .jfxt-main-content-inner').html(json._MAIN);

	$('#jfx-breadcrumbs').html(json._BREADCRUMBS);

    JFXHideLoadingAnimation();

    newScripts = new Array();
    scripts = json._JSLINKS;

	if(scripts && scripts.length){
		for(i=0; i<scripts.length; i++){
			newScripts[newScripts.length] = scripts[i];
		}
	}
    
	scripts = $('head script').get();

    foundScripts = new Array();
    for(i=0; i<scripts.length; i++){
        if(!scripts[i].src) continue;
        foundScripts[foundScripts.length] = scripts[i].src;
    }
    outer : for(i=0; i<newScripts.length; i++){
        for(i2=0; i2<foundScripts.length; i2++){
            if(foundScripts[i2]==newScripts[i]){
                continue outer;
            }
        }
        // not already existing, lets add it
        $.getScript(newScripts[i]);
    }

    $('head').append(json._HEAD);

    eval(json._JS);

    style = $('head style').get(0);
    $(style).html(json._CSS);
    $('#dynamic-style').each(function(){
        this.parentNode.removeChild(this);
    });
    style.id = 'dynamic-style';
    $('head').append(style);
    $('#jfx-workspace-inner form').each(function(){
        newAction = $(this).attr('action').replace('JFXGetAjaxContent=1', '');

        if(newAction.substring(newAction.length-1)==='?'){
            newAction = newAction.substr(0, newAction.length-1);
        }

        if($('input[type=file]', this).get().length > 0){
            // form contains a file field, we cannot ajaxify this one
            this.action = newAction
        }else{
            if(newAction.match('\\\?')){
                newAction += '&JFXGetAjaxContent=1';
            }else{
                newAction += '?JFXGetAjaxContent=1';
            }
            this.action = newAction;
        }
    });
    $('#jfx-workspace-inner form').submit(function(){
        if($('input[type=file]', this).get().length > 0){
            // contains a file field, submit normally
            return true;
        }
        ajaxSubmitOptions = {
            'success' : JFXAjaxSubmitSuccess,
            'error' : JFXAjaxSubmitError,
            'dataType' : 'text',
            'contentType' : 'text/html'
        };
	$('.jfxt-success-messages').each(function(){
		$(this).css('display', 'none');
	});
	$('.jfxt-error-messages').each(function(){
		$(this).css('display', 'none');
	});
        $.post(this.action, $(this).serialize(), JFXAjaxSubmitSuccess, 'text');

        return false;
    });

    tb_reinit('a.thickbox, area.thickbox, input.thickbox');

    // make the page tree redirect the whole page instead of load ajax content
    $('#jfx-pages-menu a').each(function(){
        if(!$(this.parentNode).hasClass('redirect')) $(this.parentNode).addClass('redirect');
    });

    $('#TB_window a').each(function(){
        if(!$(this.parentNode).hasClass('redirect')) $(this.parentNode).addClass('redirect');
    });

	$('#jfx-workspace-inner a').each(function(){
		JFXAjaxLink(this);
	});

    JFXOnloadAlways();

}





function cloneObject(o) {
    return $.extend({}, o);
 return eval(uneval(o));
}


function JFXAjaxSubmitError(rsp){
    //alert('error'+rsp);
    try{
        var json = eval(rsp);//JSON.parse(rsp);
        JFXParseAjaxContent(json);
    }catch (e){
        //$.post(JFXConfig.adminUrl, {'logdata' : rsp});
        alert('caught exception trying to decode response, length: '+rsp.length);
    }
}




function JFXToolbarHide(){

	var evalfunc = function(){
		$('#jfx-toolbar').css('left', '-2000px');
	}

    $('#jfx-toolbar').animate({
        opacity: 0
    }, 500, evalfunc);

}

function JFXToolbarShowFunction(){

	var left = (document.body.clientWidth/2-300);

	if(left <= 0) left = 200;

	$('#jfx-toolbar').css('left', Math.round(left)+'px');

    $('#jfx-toolbar').animate({
        opacity : 1
    }, 500);

}

function JFXLeftColShow(){
    clearTimeout(JFXLeftColWillHide);
    $('#jfx-leftcol-menu-abs .minimized-heading, #jfx-leftcol-menu-abs .minimized-icon').css('left', '-2000px');
    $(this).css('height', 'auto');
    $(this).css('width', '20%');
    $(this).animate({
        left: '0',
        top: '0',
        opacity: '1'
    }, 500);
}


function JFXLeftColHide(){
    $('#jfx-leftcol-menu-abs').css('overflow', 'hidden');
    $('#jfx-leftcol-menu-abs').animate({
        left: '0',
        top: '0',
        width: '100px',
        height: '24px',
        padding: '0',
        opacity: '0.6'
    }, 500, 'swing');
    $('#jfx-leftcol-menu-abs .minimized-heading, #jfx-leftcol-menu-abs .minimized-icon').css('left', 'auto');

}










